using UnityEngine;
using UnityEngine.Networking; // UnityWebRequest 需要这个命名空间
using System.Collections;
using UnityEngine.UI;
using System.Text;
using Newtonsoft.Json.Linq;
using System;

public class ChatBotController : MonoBehaviour
{
    public string api_key;   //api key
    public string initstr;   //默认台本
    public InputField input;  //用户输入  
    private JObject thread;
    private JObject run;
    private JObject answer;
    public Text aiAnswer_text;   //ai回答
    private bool isready;
    public bool over;

    public string str2;  //台本2
    public Action confirmEvent;
    public XunfeiSpeechToText speechtoText;
    void Start()
    {
        speechtoText.confirmEvent += StartGpt;
        Init();
    }

    private void Update()
    {
        //Debug.Log("over:" + over + " isready:" + isready);
        if (Input.GetKeyDown(KeyCode.Return))         //按下enter键触发提问
        {
            over = true;
        }
        if (over&&isready)
        {
            over = false;
            StartCoroutine(StartSession());

        }
    }

    public void StartGpt()
    {
        StartCoroutine(StartSession());
    }
    IEnumerator StartInit()         //会话前初始化
    {
        isready=false;
        string threadUrl = "https://api.deepbricks.ai/api/v1/threads";

        using (UnityWebRequest threadRequest = UnityWebRequest.PostWwwForm(threadUrl, ""))  //用using避免频繁发送请求造成内存泄露
        {
            threadRequest.SetRequestHeader("Authorization", api_key);
            yield return threadRequest.SendWebRequest();

            if (threadRequest.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("Thread creation error: " + threadRequest.error);
                yield break;
            }
            else
            {
                thread = JObject.Parse(threadRequest.downloadHandler.text);
                
            }

            // 解析线程信息
            string threadResponse = threadRequest.downloadHandler.text;
            ThreadResponseData threadData = JsonUtility.FromJson<ThreadResponseData>(threadResponse);
            isready=true;
        }
    }
    IEnumerator StartSession()
    {

        string user_input = GetPromptFromUser(); // 这里需要实现获取用户输入的方法
        Debug.Log("用户输入为: " + user_input);
        if (user_input == "")
        {
            Debug.Log("输入为空，请重新输入内容");
            yield break;
        }
        else
        {
            aiAnswer_text.text = "正在思考中...";
            string messageUrl = $"https://api.deepbricks.ai/api/v1/threads/{thread["id"]}/messages";
            MessageBody body = new MessageBody
            {
                role = "user",
                content = user_input
            };
            string jsonBody = JsonUtility.ToJson(body);

            using (UnityWebRequest messageRequest = UnityWebRequest.PostWwwForm(messageUrl, ""))
            {
                messageRequest.SetRequestHeader("Authorization", api_key);
                messageRequest.SetRequestHeader("Content-Type", "application/json");
                messageRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(jsonBody));
                messageRequest.downloadHandler = new DownloadHandlerBuffer();
                yield return messageRequest.SendWebRequest();

                if (messageRequest.result != UnityWebRequest.Result.Success)
                {
                    Debug.LogError("Message creation error: " + messageRequest.error);
                    yield break;
                }
            }


            string runUrl = $"https://api.deepbricks.ai/api/v1/threads/{thread["id"]}/runs";
            RunBody runBody = new RunBody
            {
                model = "gpt-4o-mini"             //用的什么ai大模型
            };
            string jsonRunBody = JsonUtility.ToJson(runBody);

            using (UnityWebRequest runRequest = UnityWebRequest.PostWwwForm(runUrl, ""))
            {
                runRequest.SetRequestHeader("Authorization", api_key);
                runRequest.SetRequestHeader("Content-Type", "application/json");
                runRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(jsonRunBody));
                runRequest.downloadHandler = new DownloadHandlerBuffer();

                yield return runRequest.SendWebRequest();

                if (runRequest.result != UnityWebRequest.Result.Success)
                {
                    Debug.LogError("Run creation error: " + runRequest.error);
                    yield break;
                }
                else
                {
                    run = JObject.Parse(runRequest.downloadHandler.text);
                }

                // 获取助手的回答
                string runResponse = runRequest.downloadHandler.text;
                RunResponseData runData = JsonUtility.FromJson<RunResponseData>(runResponse);

            }


            string answerUrl = $"https://api.deepbricks.ai/api/v1/threads/{thread["id"]}/messages?run_id={run["id"]}";

            using (UnityWebRequest answerRequest = UnityWebRequest.Get(answerUrl))
            {
                answerRequest.SetRequestHeader("Authorization", api_key);
                yield return answerRequest.SendWebRequest();

                if (answerRequest.result != UnityWebRequest.Result.Success)
                {
                    Debug.LogError("Answer retrieval error: " + answerRequest.error);
                    yield break;
                }
                else
                {
                    answer = JObject.Parse(answerRequest.downloadHandler.text);
                }

                string answerResponse = answerRequest.downloadHandler.text;
                AnswerResponseData answerData = JsonUtility.FromJson<AnswerResponseData>(answerResponse);
                string answerContent = answerData.data[0].content[0].text.value;                  // 获取到了AI的回答
                aiAnswer_text.text = answerContent;
                
            }

            input.text = "";
            over = false;
            confirmEvent?.Invoke();
        }

    }

    
    private string GetPromptFromUser()  // 用户输入的获取方法，这里需要根据实际情况实现
    {
        input.text= speechtoText.str;
        return input.text;
    }

    private void Init()                // 初始化，可以删除之前的聊天缓存
    {
        input.text = initstr;
        over = true;
        StartCoroutine(StartInit());
    }

    public void ChangeTaiBeng()        //改变台本测试成功，可以用来改变题目
    {
        input.text = str2;
        over = true;
        StartCoroutine(StartInit());
    }
}

// 定义JSON数据的类，用于反序列化
[System.Serializable]
public class ThreadResponseData
{
    public string id;
}

[System.Serializable]
public class MessageBody
{
    public string role;
    public string content;
}

[System.Serializable]
public class RunBody
{
    public string model;
}

[System.Serializable]
public class RunResponseData
{
    public string id;
}

[System.Serializable]
public class AnswerResponseData
{
    public MessageData[] data;
}

[System.Serializable]
public class MessageData
{
    public ContentData[] content;
}

[System.Serializable]
public class ContentData
{
    public TextData text;
}

[System.Serializable]
public class TextData
{
    public string value;
}
